package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.YouRongUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 友榕金服
 */
@Service
public class YouRongApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        String queryUrl = pushApiKeyParam.getCheckUrl();



        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("source", pushApiKeyParam.getApiCode());
        paramMap.put("phone", memberSourceInfo.getMobileMd5());


        log.info("【友榕金服】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
                .form(paramMap)
                .execute().body();
        log.info("【友榕金服】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer status = resultObject.getInteger("status");
        String mes = resultObject.getString("mes");

        pushApiResult.setCode( "|" + status);
        pushApiResult.setMessage(mes);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(status), "200")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();



        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("qdName", pushApiKeyParam.getApiCode());
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("price", YouRongUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("house", YouRongUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car", YouRongUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("insurance", YouRongUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("fund", YouRongUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("socital", YouRongUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("xyk", YouRongUtil.getxyk(memberSourceInfo.getXinyongka()));
        bizMap.put("wld", 0);
        bizMap.put("qyns", 0);
        bizMap.put("df", 1);
        bizMap.put("business_license", 0);
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("source", pushApiKeyParam.getApiCode());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("loan_periods", YouRongUtil.getloanTime(memberSourceInfo.getLoanTime()));


        String key=pushApiKeyParam.getApiKey();
        String iv=pushApiKeyParam.getApiSecret();

        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, key.getBytes(), iv.getBytes());
        String tranData = aes.encryptBase64(JSON.toJSONString(bizMap));


        log.info("【友榕金服】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap),tranData);
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(tranData)
                .execute().body();
        log.info("【友榕金服】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer status = resultObject.getInteger("status");

        String mes = resultObject.getString("mes");

        pushApiResult.setCode( "|" + status);
        pushApiResult.setMessage(mes);
        pushApiResult.setParamInfo(JSON.toJSONString(tranData));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(status), "0")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    public static void main(String[] args) {
        String bizMap="{\"qdName\":\"分配的渠道号\",\"name\":\"测试\",\"phone\":\"18800000000\",\"price\":50000,\"house\":1,\"car\":1,\"insurance\":0,\"fund\":1,\"socital\":0,\"xyk\":0,\"wld\":1,\"qyns\":1,\"df\":1,\"business_license\":1,\"city\":\"北京市\",\"source\":\"分配的渠道号\",\"age\":28,\"loan_periods\":36}";
        String key="byrj367920871qwe";
        String iv="byrj367920871qwe";
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, key.getBytes(), iv.getBytes());
        String tranData = aes.encryptBase64(bizMap);

        System.out.println(tranData);
    }

}
